package cn.iutils.edu.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.iutils.common.Page;
import cn.iutils.common.utils.JStringUtils;
import cn.iutils.common.BaseController;
import cn.iutils.edu.entity.Circular;
import cn.iutils.edu.service.CircularService;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
* 校务通知表 控制器
* @author iutils.cn
* @version 1.0
*/
@Controller
@RequestMapping("${adminPath}/edu/circular")
public class CircularController extends BaseController {

    @Autowired
    private CircularService circularService;

    @ModelAttribute
    public Circular get(@RequestParam(required = false) String id) {
        Circular entity = null;
        if (JStringUtils.isNotBlank(id)) {
            entity = circularService.get(id);
        }
        if (entity == null) {
            entity = new Circular();
        }
        return entity;
    }

    @RequiresPermissions("edu:circular:view")
    @RequestMapping(value = "/list")
    public String list(Model model, Page<Circular> page) {
        model.addAttribute("page", page.setList(circularService.findPage(page)));
        return "edu/circular/list";
    }

    @RequiresPermissions("edu:circular:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Circular circular,Model model) {
        model.addAttribute("circular", circular);
        return "edu/circular/form";
    }

    @RequiresPermissions("edu:circular:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(Circular circular, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        //获取上传文件的数据
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        List<String> filePath = SaveFileStrings(request);
        //初始化circular信息
        init(circular,filePath);
        circularService.save(circular);
        addMessage(redirectAttributes,"新增成功");
        return "redirect:"+ adminPath +"/edu/circular/update?id="+circular.getId();
    }

    @RequiresPermissions("edu:circular:update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(Circular circular, Model model) {
        model.addAttribute("circular", circular);
        return "edu/circular/form";
    }

    @RequiresPermissions("edu:circular:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Circular circular, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        List<String> filePath = SaveFileStrings(request);
        /*
         * 初始化circular信息
         */
        init(circular,filePath);
        circularService.save(circular);
        addMessage(redirectAttributes,"修改成功");
        return "redirect:"+ adminPath +"/edu/circular/update?id="+circular.getId();
    }



    @RequiresPermissions("edu:circular:delete")
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String delete(@PathVariable("id") String id,int pageNo,int pageSize, RedirectAttributes redirectAttributes) {
        circularService.delete(id);
        addMessage(redirectAttributes,"删除成功");
        return "redirect:"+ adminPath +"/edu/circular?pageNo="+pageNo+"&pageSize="+pageSize;
    }



    /**
     * 初始化circular信息
     * @param circular
     */
    private void init(Circular circular,List<String> filePath) {
        //发送时间
        if (circular.getSendDate()==null){
            Date now = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            circular.setSendDate(format.format(now));
        }
        //文件路径
        if (circular.getOptionsUrl() == null || circular.getOptionsUrl() == ""){
            circular.setOptionsUrl(filePath.get(0));
        }
    }


    /**
     * 保存文件信息并返回文件路径
     * @param request
     * @return
     */
    private List<String> SaveFileStrings(HttpServletRequest request) {
        //获取上传文件的数据
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        List<String> filePath = new ArrayList<String>();   //保存文件路径
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    String path="E:/springUpload/"+file.getOriginalFilename();
                    filePath.add(path);
                    //上传
                    try {
                        file.transferTo(new File(path));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return filePath;
    }
}
